/* eslint-disable */
'use strict'

const express = require('express')
const router = express.Router()
const nodemailer = require('nodemailer');
const log4js = require('log4js')
const logger = log4js.getLogger('email')
const dbconnection = require('../config/database.js')
const randomNum = require('../utils/random')
const encrypt = require('../utils/encryptTool')

const transporter = nodemailer.createTransport({ //邮箱配置
  service: 'qq',  
  auth: {  
    user: '375812401@qq.com',  
    pass: 'rapnzedgqqhacbbf' //授权码,通过QQ邮箱获取  
  }
});

const queryEmail = (mobile, callback) => {
  dbconnection.execute('SELECT email FROM USERS WHERE mobile = ?', mobile, callback)
}
const updateUser = (mobile, password, callback) => {
  dbconnection.execute('update users SET password = ? where mobile = ?', [password, mobile], callback)
}
const queryEmailPromise = mobile => new Promise((resolve, reject) => {
  queryEmail(mobile, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})
const updateUserPromise = (mobile, password) => new Promise((resolve, reject) => {
  updateUser(mobile, password, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})
const sendMailPromise = mailOptions => new Promise((resolve, reject) => {
  transporter.sendMail(mailOptions, (err, info) => {  
    if (err) {
      logger.error(err)
      reject(err)  
    } else {
      logger.info(info)
      resolve(info)
    }
  }); 
})

router.post('/', (req, res, next) => {
  logger.debug(req.body.mobile)
  queryEmailPromise(req.body.mobile).then( results => {
    logger.debug(results[0].email)
    if (results.length > 0 && results[0].email !== '') {
      let emailAddress = results[0].email
      let sendUserPwd = randomNum(8)
      let sqlNewPwd = encrypt(sendUserPwd)
      let mailOptions = {
        from: '375812401@qq.com', // 发送者
        to: emailAddress, // 接受者,可以同时发送多个,以逗号隔开
        subject: '管理系统，密码找回', // 标题
        //text: 'Hello world', // 文本
        html: `<h2>尊敬的客户:</h2><br><h3>&nbsp;&nbsp;您的新密码为：<span style="color:red">${sendUserPwd}</span></h3>`
      }
      logger.debug('newPwd', sendUserPwd, sqlNewPwd)
      Promise.all([updateUserPromise(req.body.mobile, sqlNewPwd), sendMailPromise(mailOptions)]).then(([updateRes, sendRes]) => {
        logger.info(updateRes)
        logger.info(sendRes)
        res.send({rtnCode: '000', rtnMsg: '新密码已发送至注册邮箱，请前往查看'})
      }).catch((err) => {
        logger.error(err)
        res.status(500).send({rtnCode: '500', rtnMsg: '网络问题，请稍后重试'})
      })
    } else {
      res.send({rtnCode: '000', rtnMsg: '请核对手机号填写是否正确'})
    }
  }).catch(err => {
    logger.error(err)
    res.send({rtnCode: '500', rtnMsg: '网络问题，请稍后重试'})
  })
})

module.exports = router
